package com.cmccgz.udacs_landlord_webapp.jpush;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.NotificationCompat;
import android.widget.Toast;

import com.cicadamob.contact.api.Utils.StringUtil;
import com.cmccgz.udacs_landlord_webapp.R;
import com.cmccgz.udacs_landlord_webapp.base.AppConfig;
import com.cmccgz.udacs_landlord_webapp.main.host.HostActivity;
import com.orhanobut.logger.Logger;

import org.json.JSONException;
import org.json.JSONObject;

import cn.jpush.android.api.BasicPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface;

import static android.content.Context.NOTIFICATION_SERVICE;

/**
 * Created by June on 2017-7-19.
 */

public class JpushReceiver extends BroadcastReceiver {
    private static final String TAG = "JpushReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        Logger.t(TAG).d("onReceive - " + intent.getAction());
        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            processCustomMessage(context, bundle);
            // 自定义消息不会展示在通知栏，完全要开发者写代码去处理
        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            Logger.t(TAG).d("收到了通知");
            // 在这里可以做些统计，或者做些其他工作
            BasicPushNotificationBuilder builder = new BasicPushNotificationBuilder(context);
            builder.statusBarDrawable = R.mipmap.ic_launcher;
            builder.notificationFlags = Notification.FLAG_AUTO_CANCEL
                    | Notification.FLAG_SHOW_LIGHTS;  //设置为自动消失和呼吸灯闪烁
            builder.notificationDefaults = Notification.DEFAULT_SOUND
                    | Notification.DEFAULT_VIBRATE
                    | Notification.DEFAULT_LIGHTS;  // 设置为铃声、震动、呼吸灯闪烁都要
            JPushInterface.setPushNotificationBuilder(1, builder);
        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Toast.makeText(context, "点开了通知", Toast.LENGTH_SHORT).show();
            // 在这里可以自己写代码去定义用户点击后的行为
            Intent i = new Intent(context, HostActivity.class);  //自定义打开的界面
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);
        } else {
            Logger.t(TAG).d("Unhandled intent - " + intent.getAction());
        }
    }

    private void processCustomMessage(Context context, Bundle bundle) {
        String title = bundle.getString(JPushInterface.EXTRA_TITLE);
        String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
        Logger.t(TAG).d("收到了自定义消息，消息内容是：\nTitle:" + title + "\nMessage:" + message + "\nExtras:" + extras);
        try {
            JSONObject jsonObj = new JSONObject(extras);
            String extrasValue = jsonObj.getString("extras");
            JSONObject dataObj = new JSONObject(extrasValue);
            String eventId = dataObj.getString("event_id");
            JSONObject dataObj2 = dataObj.getJSONObject("data");
            String mobile = dataObj2.getString("mobile");
            String request_id = dataObj2.getString("request_id");
            String v_mobile = dataObj2.getString("v_mobile");
            String v_name = dataObj2.getString("v_name");
            String time = dataObj2.getString("time");
            String remark = dataObj2.getString("remark");
            if ("1".equals(eventId)) {
                if (!AppConfig.getMobile(context).equals(mobile) || StringUtil.isEmpty(request_id)) {
                    return;
                }
                NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
                NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
                Intent intent = new Intent(context, AccreditActivity.class);
                intent.putExtra("requestId", request_id);
                Notification notification = builder.setContentTitle("小程序通知")
                        .setContentText("你好，访客（" + v_name + "）申请授权。").setWhen(System.currentTimeMillis())
                        .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE).setSmallIcon(R.mipmap.ic_launcher)
                        .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
                        .setContentIntent(PendingIntent.getActivity(context, 0x0001, intent, PendingIntent.FLAG_UPDATE_CURRENT))
                        .setAutoCancel(true)
                        .build();
                notificationManager.notify(1, notification);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
